package org.netty.demo.lihh.notice;

import io.netty.channel.ChannelFuture;
import org.netty.demo.lihh.notice.enumeration.ClientStateEnum;
import org.netty.demo.lihh.notice.server.NettyServer;
import org.netty.demo.lihh.notice.strategy.factory.StrategyFactory;
import org.netty.demo.lihh.notice.strategy.impl.ConnectStrategyImpl;
import org.netty.demo.lihh.notice.strategy.impl.LoginStrategyImpl;
import org.netty.demo.lihh.notice.strategy.impl.LogoutStrategyImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.InetSocketAddress;

/**
 * 消息传输协议
 */
@SpringBootApplication
public class NettyApplication implements CommandLineRunner {
  
  static {
    // 注册 策略
    StrategyFactory.register(ClientStateEnum.CLIENT_CONNECT.getType(), new ConnectStrategyImpl());
    StrategyFactory.register(ClientStateEnum.CLIENT_LOGIN.getType(), new LoginStrategyImpl());
    StrategyFactory.register(ClientStateEnum.CLIENT_LOGOUT.getType(), new LogoutStrategyImpl());
  }
  
  @Value("${netty.host}")
  private String host;
  @Value("${netty.port}")
  private int port;
  @Autowired
  private NettyServer nettyServer;
  
  public static void main(String[] args) {
    SpringApplication.run(NettyApplication.class, args);
  }
  
  @Override
  public void run(String... args) throws Exception {
    InetSocketAddress address = new InetSocketAddress(host, port);
    ChannelFuture channelFuture = nettyServer.bind(address);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> nettyServer.destroy()));
    channelFuture.channel().closeFuture().syncUninterruptibly();
  }
}
